/*
 * CmppConnectAuthenticator.java 1.0.0 Jun 12, 2008 BY wangshenggong
 * 
 * Copyright 2008 卓望信息技术(北京)有限公司 版权所有.
 *
 */
package com.aspire.nm.component.cmppserver.validate;


import javax.annotation.Resource;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.aspire.nm.component.cmppserver.filter.coder.packet.CmppConnectRespPacket;
import com.aspire.nm.component.cmppserver.runTime.SysRunTimeService;
import com.aspire.nm.component.cmppserver.runTime.UserRunTime;
import com.aspire.nm.component.commonUtil.secret.secret.SecretUtil;


/**
 * SP登陆认证过程.
 *
 * <p>descriptions</p>
 *
 *
 * @author wangshenggong
 * @version 1.0.0, Jun 12, 2008
 *
 */


@Service
public class CmppConnectAuthenticator {
	
	
	@Resource
	private SysRunTimeService sysRunTimeService;
	
	
	
	/**
	 * ASP登陆认证
	 * @return 认证状态
	 */
	@SuppressWarnings("deprecation")
    public int auth(String aspId, byte[] authenticatorSource, String ip,  int timestamp){
		
		if(sysRunTimeService.getClientConfig(aspId) == null){
			return CmppConnectRespPacket.STATUS_SRC_ADDRESS_ERR;
		}
		if(!StringUtils.isEmpty(sysRunTimeService.getClientConfig(aspId).getIp())
		        && !ip.equals(sysRunTimeService.getClientConfig(aspId).getIp())){
		    return CmppConnectRespPacket.STATUS_IP_LIMIT;
		}
		
		
		String timeString = StringUtils.leftPad(Integer.toString(timestamp), TimestampType.MMDDHHMMSS.toString().length(), "0");
		String sharedSecret = sysRunTimeService.getClientConfig(aspId).getPass();
		String tmp = aspId + new String(new byte[]{0,0,0,0,0,0,0,0,0}) + sharedSecret + timeString;
		byte[] auth = SecretUtil.ToMd5(tmp.getBytes());

		if (!ArrayUtils.isEquals(authenticatorSource, auth)) {
			return CmppConnectRespPacket.STATUS_AUTH_ERR;
		}
		if(sysRunTimeService.getClientConfig(aspId).getMaxConnNum() != 0){
		    synchronized(CmppConnectAuthenticator.class){
	            //多线程并发connect,先addSession再判断STATUS_CONNECTIONS_LIMIT
	            try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}

	            UserRunTime userRunTime = sysRunTimeService.getUserRunTime(aspId);
	            int currentConnNum = userRunTime==null?0:userRunTime.getConnNum();
	            if(currentConnNum >= sysRunTimeService.getClientConfig(aspId).getMaxConnNum()){
	                return CmppConnectRespPacket.STATUS_CONNECTIONS_LIMIT;
	            }
	        }
		}
		return CmppConnectRespPacket.STATUS_SUCCESS;
	}
	
	
	
	
	public enum TimestampType {
		MMDDHHMMSS, YYMMDDHHMM, YYYYMMDD, HHMM
	}
}
